package org.seefly.iprint.service.impl;

import org.seefly.iprint.entity.User;
import org.seefly.iprint.entity.UserExample;
import org.seefly.iprint.mapper.UserMapper;
import org.seefly.iprint.service.UserService;
import org.seefly.iprint.utils.MD5Utils;
import org.seefly.iprint.vo.LoginUserVo;
import org.seefly.iprint.vo.RegisterUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper dao;
    /**用户激活状态,手机邮箱均未激活*/
    @Value("${user.dict.noMailAndPhone}")
    private String noMailAndPhone;
    
    
    @Override
    public User login(LoginUserVo vo) {
        //首先通过用户名进行查询
        UserExample ue = new UserExample();
        ue.createCriteria().andNameEqualTo(vo.getName());
        List<User> list = dao.selectByExample(ue);
        //判断该用户名是否存在
        if(list == null || list.size() < 1) {
            return null;
        }
        User user = list.get(0);
        //获取用户盐值
        String salt = user.getSalt();
        //将用户输入的密码与数据库中盐值进行加密运算
        String pwd = MD5Utils.md5_salt(vo.getPwd(), salt);
        //将运算结果与数据库中的值进行比较
        if(user.getPsw().equals(pwd)) {
            //更新登陆次数
            user.increaseLoginCount();
            //更新登陆时间
            user.updateLoginTime();
            //写入数据库
            dao.updateByPrimaryKey(user);
            return user;
        }
        return null;
    }

    @Override
    public boolean verifyName(String name) {
        UserExample ue = new UserExample();
        ue.createCriteria().andNameEqualTo(name);
        List<User> list = dao.selectByExample(ue);
        if(list != null && list.size() > 0)
            return true;
        return false;
    }

    @Override
    public User doRegister(RegisterUserVo vo) {
        //获取随机盐值
        String salt = MD5Utils.getRandomSalt();
        //当前时间
        Date date = new Date();
        User user = new User();
        //用户名
        user.setName(vo.getName());
        //密码
        user.setPsw(MD5Utils.md5_salt(vo.getPwd(), salt));
        //邮箱
        user.setMail(vo.getMail());
        //注册时间
        user.setRegisterTime(date);
        //登陆次数
        user.setLoginCount(1);
        //登陆时间
        user.setLoginTime(date);
        //盐值
        user.setSalt(salt);
        //设置状态
        user.setStatus(Integer.getInteger(noMailAndPhone));
        dao.insert(user);
        return user;
    }
    
    
    
}
